﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ControlPropertyGenerator;
using System.Diagnostics;
using System.IO;
using System.Configuration;
using System.Xml;
using System.Xml.Linq;

namespace Launcher
{
    public partial class Start : Form
    {
        Process myProcess;
        string currentDir = Directory.GetCurrentDirectory();
        string Result = string.Empty;
        string ErrorMessage = string.Empty;
        int ExcelImageHeight = int.MinValue;
        int ExcelImageWidth = int.MinValue;

        public Start()
        {
            InitializeComponent();
            ExcelImageHeight = ExcelPicture.Height;
            ExcelImageWidth = ExcelPicture.Width;
        }

        private void generate_Click(object sender, EventArgs e)
        {
            try
            {                
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.CreateNoWindow = true;
                startInfo.FileName = ConfigurationManager.AppSettings["MSTEST"];
                startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                startInfo.Arguments = @"/testcontainer:""" + currentDir + @"\ControlPropertyGenerator.exe""";
                myProcess = Process.Start(startInfo);
                btnGenerate.Enabled = false;
                lblStatus.Text = string.Empty;
                lblSuccess.Text = string.Empty;
                progressBar1.Visible = false;
                lblProgress.Visible = false;
                ExcelPicture.Visible = false;
                lblStatus.Visible = false;
                myProcess.EnableRaisingEvents = true;
                myProcess.Exited += new EventHandler(myProcess_Exited);
                progressBar1.Visible = true;
                lblProgress.Visible = true;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.InnerException.ToString());
            }
            
        }

        // Handle Exited event and display process information. 
        private void myProcess_Exited(object sender, System.EventArgs e)
        {
            try
            {
                btnGenerate.Invoke((Action)(() => btnGenerate.Enabled = true));
                progressBar1.Invoke((Action)(() => progressBar1.Visible = false));
                lblProgress.Invoke((Action)(() => lblProgress.Visible = false));
                lblStatus.Invoke((Action)(() => lblStatus.Visible = true));
                System.Threading.Thread.Sleep(100);
                if (myProcess.ExitCode >= 0 )
                {
                    myProcess.WaitForExit();
                    GenerateTrxResults();
                    if (Result == "Passed")
                    {
                        lblSuccess.Invoke((Action)(() => lblSuccess.Text = "Properties Generated Successfully."));
                        lblSuccess.Invoke((Action)(() => lblSuccess.ForeColor = Color.Green));
                        ExcelPicture.Invoke((Action)(() => ExcelPicture.Visible = true));
                      // Generator.GenerateTemplate();
                        
                    }
                    else
                    {
                        lblSuccess.Invoke((Action)(() => lblSuccess.Text = "Properties Not Generated."));
                        lblSuccess.Invoke((Action)(() => lblSuccess.ForeColor = Color.Red));
                        lblStatus.Invoke((Action)(() => lblStatus.Text = ErrorMessage));
                        lblStatus.Invoke((Action)(() => lblStatus.ForeColor = Color.Red));

                    }
                    if (Directory.Exists(Directory.GetCurrentDirectory() + @"\TestResults"))
                    {

                        DirectoryInfo directory = new DirectoryInfo(Directory.GetCurrentDirectory() + @"\TestResults");
                        //Directory.Delete(Directory.GetCurrentDirectory() + @"\TestResults", true);
                        //delete files:
                        directory.GetFiles().ToList().ForEach(f => f.Delete());
                        //delete folders inside choosen folder
                        directory.GetDirectories().ToList().ForEach(d => d.Delete(true));
                        Directory.Delete(Directory.GetCurrentDirectory() + @"\TestResults");

                    }
                }
                else
                {
                    lblSuccess.Invoke((Action)(() => lblSuccess.Text = "Properties Not Generated."));
                    lblSuccess.Invoke((Action)(() => lblSuccess.ForeColor = Color.Red));
                    lblStatus.Invoke((Action)(() => lblStatus.Text = ErrorMessage));
                    lblStatus.Invoke((Action)(() => lblStatus.ForeColor = Color.Red));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message == null ? (ex.InnerException != null ? ex.InnerException.ToString() : string.Empty) : ex.Message);
            }
            
            
        }

        private void GenerateTrxResults()
        {
            var directory = new DirectoryInfo(currentDir + @"\TestResults");

            var myFile = (from f in directory.GetFiles()
                          orderby f.LastWriteTime descending
                          select f).First();

            string filepath = currentDir + @"\TestResults\" + myFile.ToString();
           // string filepath = Directory.GetFiles(currentDir + @"\TestResults")[0];
            File.Move(filepath, Path.ChangeExtension(filepath, ".xml"));
            filepath=filepath.Replace(".trx", ".xml");
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(filepath);
            Result = xDoc.GetElementsByTagName("UnitTestResult")[0].Attributes["outcome"].Value;                       
            if(Result.Equals("Failed"))
            {
                ErrorMessage = xDoc.GetElementsByTagName("ErrorInfo")[0].FirstChild.InnerText;                
             }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            try
            {
                Process.Start(ConfigurationManager.AppSettings["Path"] );
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message == null ? (ex.InnerException != null ? ex.InnerException.ToString() : string.Empty) : ex.Message);
            }
           
        }

        private void ExcelPicture_MouseEnter(object sender, EventArgs e)
        {
            try
            {
                ExcelPicture.Height = ExcelImageHeight + 10; 
                ExcelPicture.Width = ExcelImageWidth + 10;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message == null ? (ex.InnerException != null ? ex.InnerException.ToString() : string.Empty) : ex.Message);
            }
        }

        private void ExcelPicture_MouseLeave(object sender, EventArgs e)
        {
            try
            {
                ExcelPicture.Height = ExcelImageHeight;
                ExcelPicture.Width = ExcelImageWidth;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message == null ? (ex.InnerException != null ? ex.InnerException.ToString() : string.Empty) : ex.Message);
            }
            
        }

    }
}
